const jwt = require('jsonwebtoken')
const { User } = require('../models')
const logger = require('../utils/logger')

/**
 * 用户登录服务
 * @param {string} phone - 手机号
 * @param {string} password - 密码
 * @returns {Promise<Object>} - 登录结果
 */
async function login(phone, password) {
  try {
    // 查询用户
    const user = await User.findOne({
      where: { phone, status: 1 }
    })

    if (!user) {
      return {
        success: false,
        message: '用户不存在或已被禁用'
      }
    }

    // 验证密码
    const isPasswordValid = await user.verifyPassword(password)
    if (!isPasswordValid) {
      return {
        success: false,
        message: '密码错误'
      }
    }

    // 生成token
    const token = generateToken(user.id)

    // 更新最后登录时间
    await user.update({ last_login: new Date() })

    return {
      success: true,
      message: '登录成功',
      data: {
        token,
        user: formatUserData(user)
      }
    }
  } catch (error) {
    logger.error('Login service error:', error)
    return {
      success: false,
      message: '登录失败，请稍后再试'
    }
  }
}

/**
 * 用户注册服务
 * @param {Object} userData - 用户数据
 * @returns {Promise<Object>} - 注册结果
 */
async function register(userData) {
  try {
    const { phone, password, invitationCode } = userData

    // 检查手机号是否已注册
    const existingUser = await User.findOne({
      where: { phone }
    })

    if (existingUser) {
      return {
        success: false,
        message: '该手机号已注册'
      }
    }

    // 处理邀请码
    let inviterId = null
    if (invitationCode) {
      const inviter = await User.findOne({
        where: { invitation_code: invitationCode }
      })

      if (inviter) {
        inviterId = inviter.id
      }
    }

    // 创建用户
    const user = await User.create({
      phone,
      password,
      nickname: `用户${phone.substring(phone.length - 4)}`,
      invitation_code: generateInvitationCode(),
      inviter_id: inviterId,
      status: 1
    })

    // 生成token
    const token = generateToken(user.id)

    return {
      success: true,
      message: '注册成功',
      data: {
        token,
        user: formatUserData(user)
      }
    }
  } catch (error) {
    logger.error('Register service error:', error)
    return {
      success: false,
      message: '注册失败，请稍后再试'
    }
  }
}

/**
 * 微信登录服务
 * @param {string} code - 微信授权码
 * @param {string} invitationCode - 邀请码(可选)
 * @returns {Promise<Object>} - 登录结果
 */
async function wechatLogin(code, invitationCode) {
  try {
    // 模拟微信登录
    // 实际项目中需要调用微信API获取openid和unionid
    const openid = `openid_${Date.now()}`
    const unionid = `unionid_${Date.now()}`

    // 查询用户
    let user = await User.findOne({
      where: { openid }
    })

    let isNewUser = false
    if (!user) {
      // 处理邀请码
      let inviterId = null
      if (invitationCode) {
        const inviter = await User.findOne({
          where: { invitation_code: invitationCode }
        })

        if (inviter) {
          inviterId = inviter.id
        }
      }

      // 创建用户
      user = await User.create({
        openid,
        unionid,
        nickname: `微信用户${Date.now().toString().substring(8)}`,
        invitation_code: generateInvitationCode(),
        inviter_id: inviterId,
        status: 1
      })
      
      isNewUser = true
    }

    // 更新最后登录时间
    await user.update({ last_login: new Date() })

    // 生成token
    const token = generateToken(user.id)

    const userData = formatUserData(user)
    userData.isNewUser = isNewUser || !user.phone // 是否为新用户(未绑定手机号)

    return {
      success: true,
      message: '登录成功',
      data: {
        token,
        user: userData
      }
    }
  } catch (error) {
    logger.error('Wechat login service error:', error)
    return {
      success: false,
      message: '微信登录失败，请稍后再试'
    }
  }
}

/**
 * 生成JWT令牌
 * @param {number} userId - 用户ID
 * @returns {string} - JWT令牌
 */
function generateToken(userId) {
  return jwt.sign(
    { id: userId },
    process.env.JWT_SECRET || 'your-jwt-secret',
    { expiresIn: '7d' }
  )
}

/**
 * 生成随机邀请码
 * @returns {string} - 6位邀请码
 */
function generateInvitationCode() {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let code = ''
  for (let i = 0; i < 6; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return code
}

/**
 * 格式化用户数据
 * @param {Object} user - 用户对象
 * @returns {Object} - 格式化后的用户数据
 */
function formatUserData(user) {
  return {
    id: user.id,
    phone: user.phone,
    nickname: user.nickname,
    avatar: user.avatar,
    gender: user.gender,
    points: user.points,
    memberLevel: user.member_level,
    invitationCode: user.invitation_code
  }
}

module.exports = {
  login,
  register,
  wechatLogin,
  generateToken
}